import { defineStore } from 'pinia'
import { ref } from 'vue'
import pinia from '..'
import router from "@/router";
import { userLogin ,getStudentInfo} from "@/api/user/index";
import {reqLoginForm, StudentCardInfo} from "@/api/user/type";
//引入操作本地存储的工具方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
import { SET_USER,GET_USER,REMOVE_USER } from "@/utils/userInfo";
import {ElMessage} from "element-plus";
//创建用户小仓库
const useUserStore = defineStore('User',() => {
    const token =ref<string>(GET_TOKEN() as string)

    const userInfo = ref<StudentCardInfo>({
        id: 0,
        username: '',
        password: '',
        name: '',
        credit: 0,
        grade: 0,
        learnStatus: 0
    })

    async function login (loginForm: reqLoginForm) {
        try {
            const resLogin = await userLogin(loginForm)
            if (resLogin.code == 200) {
                SET_TOKEN(resLogin.data.token)
                console.log('学生存储token:',token.value)
                const resInfo = await getStudentInfo()
                userInfo.value = resInfo.data
                SET_USER(userInfo.value)
                console.log(userInfo.value)
                router.push('/layout')
            }
            else {
                ElMessage.error(resLogin.message)
            }
        } catch (error) {
            Promise.reject(error)
        }
    }

    return {
        token,
        userInfo,
        login
    }
})
//对外暴露获取小仓库方法
export default useUserStore

// 非setup
export function useUserStoreHook() {
    return useUserStore(pinia)
}
